package handler

import (
	"encoding/json"
	"logi-sys/cache"
	"logi-sys/moder"
	"logi-sys/pkg"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
)

func UserLogin(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"mas":  "不能为空",
			"code": 500,
		})
		return
	}

	redis_key := "redis_login" + username
	errCount, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if errCount >= 3 {
		c.JSON(200, gin.H{
			"mas":  "密码错误3次",
			"code": 500,
		})
		return
	}

	var user moder.User
	err := moder.DB.Where("username=?", username).Find(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"mas":  "查询失败",
			"code": 500,
		})
		return
	}

	if user.ID == 0 {
		c.JSON(200, gin.H{
			"mas":  "账号或密码错误",
			"code": 500,
		})
		return
	}

	if user.Password != pkg.MD5(password) {
		cache.Rdb.Incr(cache.Ctx, redis_key)
		if errCount == 2 {
			cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"mas":  "密码错误3次，封禁2小时",
				"code": 500,
			})
			return
		}
		c.JSON(200, gin.H{
			"mas":  "密码错误",
			"code": 500,
		})
		return

	}

	c.JSON(200, gin.H{
		"mas":  "密码正确",
		"code": 200,
		"data": user,
	})
	return

}

func UserRoleAdd(c *gin.Context) {
	UserId, _ := strconv.Atoi(c.PostForm("UserId"))
	RoleId, _ := strconv.Atoi(c.PostForm("RoleId"))
	if UserId == 0 || RoleId == 0 {
		c.JSON(200, gin.H{
			"mas":  "不能为空",
			"code": 500,
		})
		return
	}
	data := moder.UserRole{
		UserId: UserId,
		RoleId: RoleId,
	}
	err := moder.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"mas":  "增加失败",
			"code": 500,
		})
		return
	}

	c.JSON(200, gin.H{
		"mas":  "增加成功",
		"code": 200,
		"data": data,
	})
	return

}

func RolePermAdd(c *gin.Context) {
	RoleId, _ := strconv.Atoi(c.PostForm("RoleId"))
	PermId, _ := strconv.Atoi(c.PostForm("PermId"))
	if RoleId == 0 || PermId == 0 {
		c.JSON(200, gin.H{
			"mas":  "不能为空",
			"code": 500,
		})
		return
	}

	data := moder.RolePerm{
		RoleId: RoleId,
		PermId: PermId,
	}
	err := moder.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"mas":  "增加失败",
			"code": 500,
		})
		return
	}

	c.JSON(200, gin.H{
		"mas":  "增加成功",
		"code": 200,
		"data": data,
	})
	return

}

func UserRole(c *gin.Context) {
	UserId := c.Query("UserId")
	var data []moder.Role
	moder.DB.Table("roles").
		Joins("LEFT JOIN user_roles ON user_roles.role_id = roles.id").
		Where("user_roles.user_id =?", UserId).
		Debug().
		Find(&data)

	c.JSON(200, gin.H{
		"mas":  "成功",
		"code": 200,
		"data": data,
	})
	return

}

func RolePerm(c *gin.Context) {
	RoleId := c.Query("RoleId")
	var data []moder.Perm
	moder.DB.Table("perms").
		Joins("LEFT JOIN role_perms ON role_perms.perm_id = perms.id").
		Where("role_perms.role_id =?", RoleId).
		Find(&data)
	c.JSON(200, gin.H{
		"mas":  "成功",
		"code": 200,
		"data": data,
	})
	return
}

func UserList(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "3"))
	offset := (page - 1) * size
	if size > 50 {
		c.JSON(200, gin.H{
			"mas":  "size<=50",
			"code": 500,
		})
		return
	}
	var user []moder.User
	redis_key := "redis_list" + strconv.Itoa(page)
	result, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if result == "" {
		moder.DB.Offset(offset).Limit(size).Order("id asc").Find(&user)
		jsonData, _ := json.Marshal(user)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(result), &user)
	}

	var total int64
	moder.DB.Model(&moder.User{}).Count(&total)

	c.JSON(200, gin.H{
		"mas":   "成功",
		"code":  200,
		"data":  user,
		"total": total,
	})
	return

}

func UserDetail(c *gin.Context) {
	id := c.Query("id")
	var user moder.User
	redis_key := "redis_detail" + id
	result, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if result == "" {
		moder.DB.Where("id=?", id).First(&user)
		jsonData, _ := json.Marshal(user)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(result), &user)
	}
	c.JSON(200, gin.H{
		"mas":  "成功",
		"code": 200,
		"data": user,
	})
	return
}
